<template>
  <el-dialog :visible.sync="isShow" width="45%">
    <template #title>
      <div>{{ mode === 'add' ? '新增部门' : '编辑部门' }}</div>
    </template>
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" @focus="focusEvent">
          <el-option
            v-for="(i, index) in userList"
            :key="index"
            :value="i.username"
          >{{ i.username }}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model.trim="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  sysUserSimple,
  companyDepartmentPost,
  companyDepartmentPut
} from '@/api/departments.js'
export default {
  name: 'DialogItem',
  props: {
    //   原始数据
    initList: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      mode: 'add',
      isShow: false,
      userList: [],
      form: {
        code: '', //	string	非必须		部门编码，同级部门不可重复
        introduce: '', //	string	非必须		介绍
        manager: '', //	string	非必须		负责人名称
        name: '', //	string	非必须		部门名称
        pid: '' //	string	非必须		父级部门ID
      },
      rules: {
        // 部门编码
        code: [
          { required: true, message: '必填code', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (this.mode === 'add') {
                const result = this.initList.some((item) => {
                  return item.code === value
                })
                result
                  ? callback(new Error('请不要输入重复的部门编码'))
                  : callback()
              } else {
                const result = this.initList.some((item) => {
                  return item.code === value && item.id !== this.item.id
                })
                result
                  ? callback(new Error('请不要输入重复的部门编码'))
                  : callback()
              }
            },
            trigger: 'change'
          }
        ],
        introduce: [{ required: true, message: '必填', trigger: 'change' }],
        manager: [{ required: true, message: '必填', trigger: 'change' }],
        // 部门名称
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (this.mode === 'add') {
                const filterList = this.initList.filter((item) => {
                  return this.item.id === item.pid
                })
                filterList.some((item) => {
                  return item.name === value
                })
                  ? callback(new Error('已存在'))
                  : callback()
              } else {
                const filterList = this.initList.filter((item) => {
                  return this.item.pid === item.pid
                })
                filterList.some((item) => {
                  return item.name === value && item.id !== this.item.id
                  //  && item.id !== this.item.id 排除自己
                })
                  ? callback(new Error('已存在'))
                  : callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      //   点击当前的项
      item: ''
    }
  },
  watch: {
    isShow: {
      handler(newVal) {
        if (!newVal) {
          this.$refs.form.resetFields()
          this.form = {
            code: '', //	string	非必须		部门编码，同级部门不可重复
            introduce: '', //	string	非必须		介绍
            manager: '', //	string	非必须		负责人名称
            name: '', //	string	非必须		部门名称
            pid: '' //	string	非必须		父级部门ID
          }
        }
      }
    }
  },
  mounted() {
    this.$bus.$on('show', (bol, item, mode = 'add') => {
      this.isShow = bol
      this.item = item
      this.mode = mode
      //   console.log(this.initList)
      //   console.log('item', item)
      if (mode === 'edit') {
        this.form = JSON.parse(JSON.stringify(item))
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('show')
  },
  methods: {
    async focusEvent() {
      if (this.userList.length === 0) {
        const res = await sysUserSimple()
        this.userList = res.data
        // console.log('列表', res)
      }
    },
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          if (this.mode === 'add') {
            // 新增
            // 把当前新增项
            this.form.pid = this.item.id
            await companyDepartmentPost(this.form)
            // this.$message.success('新增成功')
            // this.$emit('getData')
            // this.isShow = false
          } else {
            // 编辑
            await companyDepartmentPut(this.form)
            // this.$message.success('编辑成功')
            // this.$emit('getData')
            // this.isShow = false
          }
          this.$message.success(this.mode === 'add' ? '新增成功' : '编辑成功')
          this.$emit('getData')
          this.isShow = false
        }
      })
    }
  }
}
</script>

<style></style>
